<template>
    <a-layout style="min-height: 100vh">
        <a-layout :style="{
            backgroundImage: 'url(' + backGroundImg + ')',
            backgroundRepeat: 'no-repeat', backgroundSize: '1600px 260px'
        }" style="background-color: #fff;">

            <a-layout-header style="background: transparent; padding: 0; margin-bottom: 20px;">
                <div style="display: flex;">
                    <div>
                        <img src="@/assets/logo-no-background.png" style="height: 60px;" @click="$router.push('/homepage_demo' + '?randomId=' + Math.random())" />
                    </div>
                    <div v-if="!login" style="margin-left: auto; margin-right: 10px; margin-top: 5px">
                        <a-button style="background: transparent; color: white" @click="onLoginShow">
                            <template #icon><user-outlined style="color: white"/></template>
                            登录
                        </a-button>
                    </div>
                    <div v-else style="margin-left: auto; margin-right: 10px; margin-top: 5px">
                        <a-dropdown>
                            <a-button style="background: transparent; color: white">
                                <user-outlined style="color: white"/>
                                {{ $store.state.username }}
                                <DownOutlined />
                            </a-button>
                            <template #overlay>
                                <a-menu @click="onMenuClick">
                                    <a-menu-item key="center">
                                        <span style="display: flex; justify-content: center;">个人中心</span>
                                    </a-menu-item>
                                    <a-menu-divider />
                                    <a-menu-item key="favorite">
                                        <span style="display: flex; justify-content: center;">我的收藏</span>
                                    </a-menu-item>
                                    <a-menu-item key="interest">
                                        <span style="display: flex; justify-content: center;">我的关注</span>
                                    </a-menu-item>
                                    <a-menu-divider />
                                    <a-menu-item key="logout">
                                        <span style="display: flex; justify-content: center;">退出登录</span>
                                    </a-menu-item>
                                </a-menu>
                            </template>
                        </a-dropdown>
                    </div>
                </div>
                <hr class="custom-divider" />
            </a-layout-header>
            <a-layout-content>
                <div style="margin-top: 30px; margin-left: 420px">
                    <a-select defaultValue="title" :options="searchOptions" v-model:value="searchField" @change="handleSelectChange" size="large" style="width: 80px" />
                    <a-input v-model:value="searchQuery" placeholder="请输入检索词" size="large" style="width: 580px; margin-left: 10px" />
                    <a-button type="primary" size="large" style="width: 100px; margin-left: 10px" @click="onSearch">
                        <template #icon><SearchOutlined /></template>
                        检索
                    </a-button>
                    <span style="color: white; margin-left: 10px; cursor: pointer" @click="$router.push('/advancedSearch_demo')">高级检索></span>
                </div>
                <div id="paper-box" style="margin-left: 300px; margin-top: 50px; width: 1000px; border-radius: 4px 4px 4px 4px;">
                    <a-tabs v-model:activeKey="activeKey" size="large" style="margin-left: 20px; margin-right: 20px">
                        <a-tab-pane key="1" tab="更新速递">
                            <a-list style="min-height: 350px;" :loading="initLoading" item-layout="vertical" size="large"
                                    :data-source="list" :split="false">
                                <template #loadMore>
                                    <div
                                            v-if="!initLoading && !loading"
                                            :style="{ textAlign: 'center', height: '32px', lineHeight: '32px', marginBottom:'10px' }"
                                    >
                                        <a-button @click="onLoadMore">加载更多</a-button>
                                    </div>
                                </template>
                                <template #renderItem="{ item }">
                                    <a-list-item>
                                        <a-card :loading="item.loading" style="border-width: 2px;">
                                            <p :style="{ color: item.isTitleHovered ? '#5C7DFF' : '#1151D9', textDecoration: item.isTitleHovered ? 'underline' : 'none' , fontSize: '20px', cursor: 'pointer'}"
                                               @mouseover="item.isTitleHovered = true"
                                               @mouseleave="item.isTitleHovered = false"
                                               @click="handleRead(item.paper_id)">
                                                {{item.title}}
                                            </p>
                                            <p style="color: #6C6C6C">
                                                <!-- 作者列表，可跳转至作者界面 -->
                                                作者:
                                                <template v-for=" (author, index) in item.authors"
                                                          :key="author.author_id">
                                                    <u :style="{ color: author.isHovered ? '#6C6C6C' : '#0B0E47', textDecoration: author.isHovered ? 'underline' : 'none', cursor: 'pointer' }"
                                                       @mouseover="author.isHovered = true"
                                                       @mouseleave="author.isHovered = false"
                                                       @click="handleAuthor(author.author_id)">
                                                        {{ author.author_name }}
                                                    </u>
                                                    <span v-if="index < item.authors.length - 1">; </span>
                                                </template>
                                            </p>
                                            <a-typography-paragraph
                                                    :ellipsis="ellipsis ? { rows: 3, expandable: true, symbol: '展开∨' } : false"
                                                    :content="item.paper_abstract"
                                            />
                                            <p style="color: #6C6C6C; line-height: 2">
                                                所属学科:
                                                <template v-for=" (cat, index) in item.categories">
                                                    <span style="color: #0B0E47">{{ cat }}
                                                    </span>
                                                    <span v-if="index < item.categories.length - 1">; </span>
                                                </template>
                                                <br/>
                                                <span v-if="item.journal_ref">
                                                    发表期刊: <span style="color: #0B0E47">{{ item.journal_ref }}</span>
                                                    <br/>
                                                </span>
                                                更新时间:
                                                <span style="color: #0B0E47">{{item.update_date}}</span>
                                            </p>
                                            <a-button v-if="item.favorite" :size="large" style="background-color: #EFEFEF" @click="handleFavorite(item.paper_id)">
                                                <template #icon>
                                                    <star-filled :style="{color: '#FCCA00'}"/>
                                                </template>
                                                取消收藏
                                            </a-button>
                                            <a-button v-else :size="large" style="background-color: #EFEFEF" @click="handleFavorite(item.paper_id)">
                                                <template #icon>
                                                    <StarOutlined />
                                                </template>
                                                加入收藏
                                            </a-button>
                                            <a-button :size="large" style="margin-left: 10px; background-color: #EFEFEF" @click="handlePDF(item.url)">
                                                <template #icon>
                                                    <ReadOutlined />
                                                </template>
                                                在线阅读
                                            </a-button>
                                            <a-button :size="large" style="margin-left: 10px; background-color: #EFEFEF" @click="$router.push('/similar_paper?paper_id=' + item.paper_id)">
                                                <template #icon>
                                                    <PaperClipOutlined />
                                                </template>
                                                查看相似论文
                                            </a-button>
                                        </a-card>
                                    </a-list-item>
                                </template>
                            </a-list>
                        </a-tab-pane>
                        <a-tab-pane key="2" tab="为您推荐" :disabled="!login">
                            <a-list style="min-height: 350px;" :loading="mock_initLoading" item-layout="vertical" size="large"
                                    :data-source="mock_list" :split="false">
                                <template #loadMore>
                                    <div
                                            v-if="!mock_initLoading && !mock_loading"
                                            :style="{ textAlign: 'center', height: '32px', lineHeight: '32px', marginBottom:'10px' }"
                                    >
                                        <a-button @click="mock_onLoadMore">加载更多</a-button>
                                    </div>
                                </template>
                                <template #renderItem="{ item }">
                                    <a-list-item>
                                        <a-card :loading="item.mock_loading" style="border-width: 2px;">
                                            <p :style="{ color: item.isTitleHovered ? '#5C7DFF' : '#1151D9', textDecoration: item.isTitleHovered ? 'underline' : 'none' , fontSize: '20px', cursor: 'pointer'}"
                                               @mouseover="item.isTitleHovered = true"
                                               @mouseleave="item.isTitleHovered = false"
                                               @click="handleRead(item.paper_id)">
                                                {{item.title}}
                                            </p>
                                            <p style="color: #6C6C6C">
                                                <!-- 作者列表，可跳转至作者界面 -->
                                                作者:
                                                <template v-for=" (author, index) in item.authors"
                                                          :key="author.author_id">
                                                    <u :style="{ color: author.isHovered ? '#6C6C6C' : '#0B0E47', textDecoration: author.isHovered ? 'underline' : 'none', cursor: 'pointer' }"
                                                       @mouseover="author.isHovered = true"
                                                       @mouseleave="author.isHovered = false"
                                                       @click="handleAuthor(author.author_id)">
                                                        {{ author.author_name }}
                                                    </u>
                                                    <span v-if="index < item.authors.length - 1">; </span>
                                                </template>
                                            </p>
                                            <a-typography-paragraph
                                                    :ellipsis="ellipsis ? { rows: 3, expandable: true, symbol: '展开∨' } : false"
                                                    :content="item.paper_abstract"
                                            />
                                            <p style="color: #6C6C6C; line-height: 2">
                                                所属学科:
                                                <template v-for=" (cat, index) in item.categories">
                                                    <span style="color: #0B0E47">{{ cat }}
                                                    </span>
                                                    <span v-if="index < item.categories.length - 1">; </span>
                                                </template>
                                                <br/>
                                                <span v-if="item.journal_ref">
                                                    发表期刊: <span style="color: #0B0E47">{{ item.journal_ref }}</span>
                                                    <br/>
                                                </span>
                                                更新时间:
                                                <span style="color: #0B0E47">{{item.update_date}}</span>
                                            </p>
                                            <a-button v-if="item.favorite" :size="large" style="background-color: #EFEFEF" @click="handleFavorite(item.paper_id)">
                                                <template #icon>
                                                    <star-filled :style="{color: '#FCCA00'}"/>
                                                </template>
                                                取消收藏
                                            </a-button>
                                            <a-button v-else :size="large" style="background-color: #EFEFEF" @click="handleFavorite(item.paper_id)">
                                                <template #icon>
                                                    <StarOutlined />
                                                </template>
                                                加入收藏
                                            </a-button>
                                            <a-button :size="large" style="margin-left: 10px; background-color: #EFEFEF" @click="handlePDF(item.url)">
                                                <template #icon>
                                                    <ReadOutlined />
                                                </template>
                                                在线阅读
                                            </a-button>
                                            <a-button :size="large" style="margin-left: 10px; background-color: #EFEFEF" @click="$router.push('/similar_paper?paper_id=' + item.paper_id)">
                                                <template #icon>
                                                    <PaperClipOutlined />
                                                </template>
                                                查看相似论文
                                            </a-button>
                                        </a-card>
                                    </a-list-item>
                                </template>
                            </a-list>
                        </a-tab-pane>
                        <template #rightExtra>
                            <div v-if="!login">
                                <a-button style="background-color: #3fa4fc; color: white" @click="onLoginShow">
                                    登录
                                </a-button>
                                <span style="margin-right: 500px"> 后体验个性化推荐功能</span>
                            </div>
                        </template>
                    </a-tabs>
                </div>
                <a-modal v-model:visible="loginShow" :footer="null" centered width="800px">
                    <div style="display: flex;">
                        <img src="@/assets/cut-theone-scholar-logo.png" style="width: 400px;">
                        <div>
                            <div style="color: #0B0E47; font-weight: 500; font-size: 30px">欢迎登录</div>
                            <a-form
                                    :model="loginForm"
                                    style="margin-top: 20px; max-width: 300px;"
                                    @finish="onLoginFinish">
                                <a-form-item
                                        label="账号"
                                        name="username"
                                        :rules="[{ required: true, message: '请输入账号' }]">
                                    <a-input v-model:value="loginForm.username">
                                        <template #prefix>
                                            <UserOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input>
                                </a-form-item>

                                <a-form-item
                                        label="密码"
                                        name="password"
                                        :rules="[{ required: true, message: '请输入密码' }]">
                                    <a-input-password v-model:value="loginForm.password">
                                        <template #prefix>
                                            <LockOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input-password>
                                </a-form-item>

                                <a-form-item style="margin-top: -10px">
                                    <a-form-item name="remember" no-style>
                                        <a-checkbox v-model:checked="loginForm.remember">记住密码</a-checkbox>
                                    </a-form-item>
                                </a-form-item>

                                <a-form-item style="margin-top: -10px">
                                    <a-button :disabled="disabled" type="primary" html-type="submit" style="width: 100%;">
                                        登录
                                    </a-button>
                                    <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 10px">
                                        <a @click="onRegisterShow">注册新用户</a>
                                        <a style="float: right;">忘记密码</a>
                                    </div>
                                </a-form-item>
                            </a-form>
                        </div>
                    </div>
                </a-modal>
                <a-modal v-model:visible="registerShow" :footer="null" centered width="800px">
                    <div style="display: flex;">
                        <img src="@/assets/cut-theone-scholar-logo.png" style="width: 400px;">
                        <div>
                            <div style="color: #0B0E47; font-weight: 500; font-size: 30px">注册账号</div>
                            <a-form
                                    layout="horizontal"
                                    ref="formRef"
                                    :model="registerForm"
                                    style="margin-top: 20px"
                                    @finish="onRegisterFinish">
                                <a-form-item
                                        label="账号"
                                        name="username"
                                        :rules="[{ required: true, message: '请设置用户名' },{ message: '用户名已被占用', validator: validateUsername}]">
                                    <a-input v-model:value="registerForm.username">
                                        <template #prefix>
                                            <UserOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input>
                                </a-form-item>

                                <a-form-item
                                        label="密码"
                                        name="password"
                                        :rules="[{ required: true, message: '请设置密码' }]">
                                    <a-input-password v-model:value="registerForm.password">
                                        <template #prefix>
                                            <LockOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input-password>
                                </a-form-item>

                                <a-form-item
                                        label="身份"
                                        name="identity"
                                        :rules="[{ required: true, message: '请选择身份' }]">
                                    <a-select v-model:value="registerForm.identity" :options="identityOptions" placeholder="请选择身份"/>
                                </a-form-item>

                                <a-form-item
                                        label="邮箱"
                                        name="email">
                                    <a-input v-model:value="registerForm.email" placeholder="请绑定邮箱">
                                        <template #prefix>
                                            <mail-outlined class="site-form-item-icon" />
                                        </template>
                                    </a-input>
                                </a-form-item>

                                <a-form-item>
                                    <a-button :disabled="registerDisabled" type="primary" html-type="submit" style="width: 70%">
                                        注册
                                    </a-button>
                                    <a-button style="margin-left: 5%; width: 25%" @click="() => formRef.resetFields()">
                                        清空
                                    </a-button>
                                </a-form-item>
                            </a-form>
                        </div>
                    </div>
                </a-modal>
            </a-layout-content>
            <a-layout-footer style="background: #000; text-align: center">
                <p style="color:#fff">©{{ new Date().getFullYear() }} {{ systemTitle }}</p>
                <p style="color:#fff">
                    <a @click.prevent="$router.push('/about')">关于</a>&nbsp;|&nbsp;
                    <a>开发团队</a>&nbsp;|&nbsp;
                    <a href="https://gitee.com/shenyang-theone/theone-recsys">了解更多</a>
                </p>
            </a-layout-footer>
        </a-layout>
    </a-layout>
</template>

<script>
import {defineComponent, reactive, toRefs, ref, onMounted, nextTick, computed} from "vue";
import {
    UserOutlined,
    DownOutlined,
    SearchOutlined,
    StarOutlined,
    StarFilled,
    ReadOutlined, PaperClipOutlined, LockOutlined, MailOutlined
} from "@ant-design/icons-vue";
import {useRoute, useRouter} from "vue-router";
import {search} from "@/api/post/search";
import {cloneDeep} from "lodash-es";
import globalVariable from "@/components/mathJax/globalVariable";
import {useStore} from "vuex";
import {login} from "@/api/post/login";
import {user_info} from "@/api/post/user_info";
import {notification} from "ant-design-vue";
import {logout as logout_request} from "@/api/post/logout";
import {favorite} from "@/api/post/favorite";
import {register} from "@/api/post/register";
import {validate_username} from "@/api/post/validate_username";
import {add_search} from "@/api/post/add_search";
import {browsing} from "@/api/post/browsing";

export default defineComponent({
    components: {
        MailOutlined,
        LockOutlined,
        SearchOutlined,
        UserOutlined,
        DownOutlined,
        StarOutlined,
        StarFilled,
        ReadOutlined,
        PaperClipOutlined,
    },
    setup(){

        // -------------onMounted钩子，组件挂载完毕异步加载数据--------------
        onMounted(() => {
            state.login = !store.state.logout
            // 调用搜索接口
            search(state.searchQuery, state.searchField, state.max_length, state.offset, state.sort, state.tagsChecked, state.startDate, state.endDate).then((response) => {
                if (response.data.status.code === 0) {
                    // 请求成功
                    state.initLoading = false;
                    state.data = response.data.data.paperList;
                    state.list = response.data.data.paperList;
                    state.offset++;
                }
            })
            checkLaTex()

            // 处理数据：用于设置悬停样式
            state.list.forEach((paper) => {
                // 区分Title，为每个paper设置单独的isTitleHovered属性
                paper.isTitleHovered = false;
                paper.authors.forEach((author) => {
                    // 区分author，为每个author设置单独的isHovered属性
                    author.isHovered = false;
                });
            });

            // 调用mock推荐接口,实际仍然调用search，但是指定关键词为Neural Network
            search('Neural Network', 'title', state.max_length, state.offset, state.sort, state.tagsChecked, state.startDate, state.endDate).then((response) => {
                if (response.data.status.code === 0) {
                    // 请求成功
                    state.mock_initLoading = false;
                    state.mock_data = response.data.data.paperList;
                    state.mock_list = response.data.data.paperList;
                    state.mock_offset++;
                }
            })

            // 处理数据：用于设置悬停样式
            state.list.forEach((paper) => {
                // 区分Title，为每个paper设置单独的isTitleHovered属性
                paper.isTitleHovered = false;
                paper.authors.forEach((author) => {
                    // 区分author，为每个author设置单独的isHovered属性
                    author.isHovered = false;
                });
            });
        });

        // ----------------定义的function，由下至上编写---------------
        const validateUsername = (rule, value) => {
            return new Promise((resolve, reject) => {
                if (value.length === 0) {
                    resolve()
                }
                validate_username(value).then((response) => {
                    const { code, message } = response.data.status
                    if (code === 0) {
                        resolve()
                    } else {
                        reject(message)
                    }
                })
            })
        }

        const handleFavorite = (paper_id) => {
            // 点击收藏/取消：数据存入数据库中，但是前端直接修改收藏状态，无需重新获取数据
            favorite(paper_id).then(() => {
                // 请求成功后，前端处理数据
                state.list.forEach((paper) => {
                    if (paper.paper_id === paper_id) {
                        paper.favorite = !paper.favorite;
                    }
                });
            });
        }

        const handleAuthor = (author_id) => {
            window.open('/author_show_demo?author_id=' + author_id, '_blank')
        }

        const handlePDF = (url) => {
            // 使用split方法按照'/'分割字符串，取得最后一个元素
            const parts = url.split("/");
            // 取得最后一个元素，即'0707.3421'
            const paper_id = parts[parts.length - 1];
            window.open('https://arxiv.org/pdf/' + paper_id + '.pdf', '_blank')
        }

        const handleRead = (paper_id) => {
            // 记录用户浏览论文历史
            browsing(paper_id).then((response) => {
                if(response.data.status.code === 0){
                    console.log("浏览埋点设置成功")
                }
            })
            window.open('/paper_show_demo?paper_id=' + paper_id, '_blank')
        }

        const onMenuClick = ({ key }) => {
            switch (key) {
                case 'center': {
                    window.open('/user_center_demo', '_blank')
                    break
                }
                case 'favorite': {
                    window.open('/user_center_demo?currentKey=3&&selectedKeys=3&&openKeys=2', '_blank')
                    break
                }
                case 'interest': {
                    window.open('/user_center_demo?currentKey=4&&selectedKeys=4&&openKeys=2', '_blank')
                    break
                }
                // case 'subscribe': {
                //     router.push('/subscribe')
                //     break
                // }
                case 'logout': {
                    logout()
                }
            }
        }

        const logout = () => {
            state.login = false;
            logout_request()
                    .then((response) => {
                        if (response.data) {
                            //退出成功
                            store.commit('SET_LOGOUT', true)
                            store.commit('CLEAR_USER_INFO')
                            store.commit('CLEAR_TOKEN')
                            // 清空本地存储的数据
                            sessionStorage.clear()
                            // 其他操作...
                        }
                    })
                    .catch(() => {
                        store.commit('SET_LOGOUT', true)
                        store.commit('CLEAR_USER_INFO')
                        store.commit('CLEAR_TOKEN')
                    })
        }

        const onRegisterFinish = values => {
            register(values.email, values.username, values.password, values.identity).then((response) => {
                if (response.data.status.code === 0) {
                    //注册成功
                    store.commit('CLEAR_USER_INFO')
                    store.commit('SET_TOKEN', response.data.data)
                    notification['success']({
                        message: '成功',
                        description: '注册成功',
                    })
                    state.loginShow = true;
                    state.registerShow = false;
                } else {
                    notification['error']({
                        message: '错误',
                        description: response.data.status.message,
                    })
                }
            })
        }

        const onLoginFinish = values => {
            login(values.username, values.password, values.remember).then((response) => {
                store.commit('CLEAR_USER_INFO')
                store.commit('CLEAR_TOKEN')
                if (response.data.status.code === 0) {
                    state.loginShow = false;
                    state.login = true;

                    store.commit('SET_LOGOUT', false)
                    //成功后继续请求用户信息
                    store.commit('SET_TOKEN', response.data.data)
                    console.log(response.data.data)
                    user_info()
                            .then((response) => {
                                if (response.data.status.code === 0) {
                                    // 成功后设置用户信息
                                    store.commit('SET_USER_INFO', response.data.data.user)
                                    console.log(response.data.data.user)
                                    // if ($route.redirectedFrom) {
                                    //     router.push({
                                    //         path: decodeURIComponent($route.redirectedFrom.fullPath),
                                    //     })
                                    // } else {
                                    //     router.push('/')
                                    // }
                                } else {
                                    notification['error']({
                                        message: '错误',
                                        description: response.data.status.message,
                                    })
                                }
                            })
                            .catch()
                } else if (response.data.status.code === 1 || response.data.status.code === 2) {
                    notification['warning']({
                        message: '登录失败',
                        description: '您提供的用户名或密码无效',
                    })
                } else {
                    notification['error']({
                        message: '错误',
                        description: response.data.status.message,
                    })
                }
            })

        };

        const onRegisterShow = () => {
            state.loginShow = false;
            state.registerShow = true;
        };

        const onLoginShow = () => {
            state.loginShow = true;
        };

        const registerDisabled = computed(() => {
            return !(registerForm.username && registerForm.password && registerForm.identity);
        });

        // const loginDisabled = computed(() => {
        //     return !(loginForm.username && loginForm.password);
        // });

        const checkLaTex = () => {
            globalVariable.initMathjaxConfig();
            globalVariable.MathQueue();
        }

        const mock_onLoadMore = () => {
            state.mock_loading = true;
            state.mock_list = state.mock_data.concat(
                    [...new Array(state.max_length)].map(() => ({
                        mock_loading: true,
                    })),
            );
            search('Neural Network', 'title', state.max_length, state.offset, state.sort, state.tagsChecked, state.startDate, state.endDate).then((response) => {
                if (response.data.status.code === 0) {
                    // 请求成功
                    const newData = state.mock_data.concat(response.data.data.paperList);
                    state.mock_loading = false;
                    state.mock_data = newData;
                    state.mock_list = newData;
                    state.mock_offset++;
                    nextTick(() => {
                        // Resetting window's offsetTop so as to display react-virtualized demo underfloor.
                        // In real scene, you can using public method of react-virtualized:
                        // https://stackoverflow.com/questions/46700726/how-to-use-public-method-updateposition-of-react-virtualized
                        window.dispatchEvent(new Event('resize'));
                    });
                }
            })
        };

        const onLoadMore = () => {
            state.loading = true;
            state.list = state.data.concat(
                    [...new Array(state.max_length)].map(() => ({
                        loading: true,
                    })),
            );
            search(state.searchQuery, state.searchField, state.max_length, state.offset, state.sort, state.tagsChecked, state.startDate, state.endDate).then((response) => {
                if (response.data.status.code === 0) {
                    // 请求成功
                    const newData = state.data.concat(response.data.data.paperList);
                    state.loading = false;
                    state.data = newData;
                    state.list = newData;
                    state.offset++;
                    nextTick(() => {
                        // Resetting window's offsetTop so as to display react-virtualized demo underfloor.
                        // In real scene, you can using public method of react-virtualized:
                        // https://stackoverflow.com/questions/46700726/how-to-use-public-method-updateposition-of-react-virtualized
                        window.dispatchEvent(new Event('resize'));
                    });
                }
            })
        };

        const handleSelectChange = value => {
            state.searchField = value;
            console.log('select:', value);
        }

        //点击检索按钮触发事件
        const onSearch = () => {
            // 记录检索历史
            let search_str = '';
            // 检索词不为空添加检索词字段
            if(state.searchQuery !== ''){
                search_str = search_str+state.searchField+"="+state.searchQuery;
            }
            // 学科限定不为空添加学科限定字段
            if(state.subjectChoose.length > 0){
                // 不同检索字段间用分号间隔
                if(search_str !== '') search_str += "; ";
                search_str = search_str+"subjects=["+state.subjectChoose+"]";
            }
            // 前端判断非空才触发后端add_search方法，否则该条记录无意义
            if(search_str !== ''){
                add_search(search_str).then((response) => {
                    if (response.data.status.code === 0) {
                        // 请求成功
                        console.log("记录检索历史成功")
                    }
                })
            }

            // 处理tagsChecked
            // 检查 subjectChoose 数组中是否包含 'phys'
            let physIndex = state.subjectChoose.indexOf('phys');
            // 转换后的结果，注意要定义新的变量（创建state.subjectChoose的一个独立拷贝），以免影响前端显示
            let subjectChoose2 = state.subjectChoose.slice()
            if (physIndex !== -1) {
                // 如果包含 'phys'，将它替换为phys下的所有二级分类学科
                subjectChoose2.splice(physIndex, 1, ...(['astro-ph', 'cond-mat', 'gr-qc', 'hep-ex', 'hep-lat', 'hep-ph', 'hep-th', 'math-ph', 'nlin', 'nucl-ex', 'nucl-th', 'physics', 'quant-ph']));
            }
            state.tagsChecked = subjectChoose2
            // 通过使用 slice() 方法创建 state.tagsChecked 的一个浅拷贝，将其转换为标准数组
            router.push('/ordinarySearch_demo?searchField='+state.searchField+'&searchQuery='+state.searchQuery+'&tagsChecked='+JSON.stringify(state.tagsChecked.slice()))
        }

        // --------------------定义的vue变量------------------------
        const store = useStore()
        const $route = useRoute()
        const router = useRouter()

        // --------------------定义的响应数据-----------------------
        const state = reactive({
            mock_initLoading: true,
            mock_loading: false,
            mock_data:[],
            mock_list:[],
            mock_offset: 1,
            formRef: null,
            registerShow: false,
            loginShow: false,
            login: false,
            ellipsis: true,
            startDate: '',
            endDate: '',
            offset: 1,
            max_length: 3,
            tagsChecked: [],            //标签筛选首页中呈现的已经选中的标签
            sort:"time",
            data:[],
            list:[],
            initLoading: true,
            loading: false,
            activeKey: "1",             // 标签页默认显示页
            // physicsChoose: 'all',       // physics所属的二级学科，默认值all
            subjectChoose:[],
            searchOptions: [
                { label: '标题', value: 'title' },
                { label: '摘要', value: 'abstract' },
                { label: '作者', value: 'author' },
                { label: '期刊', value: 'journal' },
            ],
            searchQuery: '',
            searchField: 'title',
            backGroundImg: require('@/assets/background2.png')
        })

        const registerForm = reactive({
            username: '',
            password: '',
            identity: null,
            email: '',
        });

        const loginForm = reactive({
            username: '',
            password: '',
            remember: false,
        });

        // ----------------------定义的常量--------------------
        const identityOptions = [{
            label: '学生',
            value: '1',
        }, {
            label: '教授',
            value: '2',
        }, {
            label: '副教授',
            value: '3',
        }, {
            label: '讲师',
            value: '4',
        }]

        // ----------------------return函数-------------------
        return {
            mock_onLoadMore,
            validateUsername,
            identityOptions,
            handleFavorite,
            handleAuthor,
            handlePDF,
            handleRead,
            onRegisterShow,
            onLoginShow,
            onRegisterFinish,
            onLoginFinish,
            registerDisabled,
            // loginDisabled,
            registerForm,
            loginForm,
            onLoadMore,
            handleSelectChange,
            onSearch,
            onMenuClick,
            ...toRefs(state),
            systemTitle: process.env.VUE_APP_TITLE,
        }
    }
})
</script>

<style scoped>

/*论文展示的背景板*/
#paper-box{
    background-color: white;
    opacity: 0.86;
    box-shadow: 0px 2px 10px 1px rgba(0, 0, 0, 0.4);
}

/*学科限定的默认描述*/
#description-text {
    position: relative;
    top: -20px;
    left: 10px;
    font-weight: bold;
    font-size: 13px;
    color: rgba(190, 190, 190, 0.8);
    z-index: 1;
}

/*学科限定框的板块名*/
#overlay-text {
    position: relative;
    top: -25px;
    left: 10px;
    font-weight: bold;
    font-size: 16px;
    color: white;
    z-index: 1;
}

/*学科限定框*/
#subject-box {
    background-color: rgba(255, 255, 255, 0.1);
    padding: 10px;
    border-radius: 4px 4px 4px 4px;
}

/*分割线*/
.custom-divider {
    border: none;
    height: 1px;
    background-color: #BBBBBB;
}
</style>